package com.cyys.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * MD5算法
 * 提供密码加密
 * @author LC
 *
 */
public class MD5Util {
	/**
	 * create a digest for a buffer of bytes.
	 *
	 * @param buffer
	 * @param key
	 * @return
	 */
	private static byte[] getKeyedDigest(byte[] buffer) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(buffer);
			return md5.digest();
		} catch (NoSuchAlgorithmException e) {
		}
		return null;
	}
	/**
	 * byte to hex
	 * @param b
	 * @return
	 */
	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
			if (n < b.length - 1)
				hs = hs + "";
		}
		return hs;
	}

	public static String calcMD5(String psw){
		synchronized (MD5Util.class) {
			return byte2hex(getKeyedDigest(psw.getBytes()));
		}
	}

	public static void main(String[] args) {
		System.out.println(MD5Util.calcMD5("warning@20180331"));
	}
}